package com.baipiao.permission.backend.config.security;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import com.baipiao.permission.backend.comm.columns.UserEntityColumns;
import com.baipiao.permission.backend.entity.response.ResData;
import com.baipiao.permission.backend.entity.response.ResStatusEnum;
import com.baipiao.permission.backend.entity.sys.UserEntity;
import com.baipiao.permission.backend.service.sys.UserServiceImpl;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description: 登录成功处理逻辑
 */
@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    UserServiceImpl UserServiceImpl;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                        Authentication authentication) throws IOException {
        UserDetails obj = (UserDetails) authentication.getPrincipal();
        Integer id = Integer.parseInt(obj.getUsername());
        //更新用户最新登录时间
        UserServiceImpl.updateById(new UserEntity()
                .setId(id)
                .setLastLoginDate(LocalDateTime.now()));
        //返回用户信息
        UserEntity user = UserServiceImpl.getOne(new LambdaQueryWrapper<UserEntity>()
                .eq(UserEntity::getId, id)
                .select(UserEntityColumns.getGeneralInfo()));//设置返回列，不包括敏感信息
        //返回权限列表
        List<String> list = new ArrayList<>();
        obj.getAuthorities().stream()
                .filter(i -> !i.getAuthority().contains("ROLE_"))
                .forEach(i -> list.add(i.getAuthority()));
        Map<String, Object> resData = new HashMap<>();
        //返回json数据
        resData.put("user", user);
        resData.put("permissionList", list);
        String res = JSONObject.toJSONString(ResData.success(ResStatusEnum.login, resData));// 200,认证成功
        httpServletResponse.setContentType("text/json;charset=utf-8");
        httpServletResponse.getWriter().write(res);
    }
}
